package cn.yangliu.webflux.config;

import java.util.List;

import cn.yangliu.webflux.comm.JsonResult;
import com.google.common.base.Preconditions;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapterRegistry;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.web.reactive.HandlerResult;
import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
import org.springframework.web.reactive.result.method.annotation.ResponseBodyResultHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 统一响应结构体
 *
 * @author 杨柳
 * @date 2019-12-08
 */
public class MyHandlerResultHandler extends ResponseBodyResultHandler {
    public MyHandlerResultHandler(List<HttpMessageWriter<?>> writers, RequestedContentTypeResolver resolver) {
        super(writers, resolver);
    }

    public MyHandlerResultHandler(List<HttpMessageWriter<?>> writers, RequestedContentTypeResolver resolver, ReactiveAdapterRegistry registry) {
        super(writers, resolver, registry);
    }

    @Override
    public boolean supports(HandlerResult handlerResult) {
        return super.supports(handlerResult);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Mono<Void> handleResult(ServerWebExchange serverWebExchange, HandlerResult handlerResult) {
        Object returnValue = handlerResult.getReturnValue();
        Preconditions.checkNotNull(returnValue, "response is null!");
        MethodParameter bodyTypeParameter = handlerResult.getReturnTypeSource();
        Mono<JsonResult<Object>> body;
        if (returnValue instanceof Mono) {
            body = ((Mono<Object>) returnValue).map(JsonResult::getInstance)
                    .defaultIfEmpty(JsonResult.getInstance());
        }else {
            body = Mono.just((JsonResult<Object>)returnValue);
        }


        return writeBody(body, bodyTypeParameter, serverWebExchange);

    }
}
